package csc.daonjpa.java.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.PersistenceException;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.hibernate.exception.ConstraintViolationException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import csc.daonjpa.java.domain.Account;
import csc.daonjpa.java.domain.Customer;
import csc.daonjpa.java.domain.TargetAccount;
import csc.daonjpa.java.domain.TransferTransaction;
import csc.daonjpa.java.service.BankService;

@Controller
public class TransferTransactionController {
	private static final Logger LOG = Logger
			.getLogger(CustomerController.class);

	private BankService bankService;

	public BankService getBankService() {
		return bankService;
	}

	@Autowired
	public void setBankService(BankService bankService) {
		this.bankService = bankService;
	}

	/**
	 * Create a transaction
	 */
	@RequestMapping(value = "/addTransaction", method = RequestMethod.POST)
	public String addTransaction(HttpServletRequest request, Model model) {

		// Create a transfer transaction from data sent by the .jsp
		String srcAccNumber = request.getParameter("srcAccountNumber");
		String tarAccNumber = request.getParameter("tarAccountNumber");
		long amount = Long.parseLong(request.getParameter("amount"));
		Date date = new Date();

		// Bi-directional steps
		// 1_create account
		Account srcAcc = bankService.getAccountByAccNumber(srcAccNumber);
		long remaining = srcAcc.getAvailableAmount();
		if (remaining < amount) {

		} else {
			long newAmount = remaining - amount;
			srcAcc.setAvailableAmount(newAmount);
			bankService.mergeAccount(srcAcc);
		}
		// 2_create Target account
		TargetAccount tarAcc = bankService
				.getTargetAccountByAccNum(tarAccNumber);
		// 3_create transfer transaction obj
		TransferTransaction transaction = new TransferTransaction(srcAcc,
				tarAcc, amount, date);

		// 4_Add the transaction obj into account & targetAccount obj
		srcAcc.addTransaction(transaction);
		tarAcc.addTransaction(transaction);

		// 5_Set the srcAcc & tarAcc again
		transaction.setSrcAcc(srcAcc);
		transaction.setTarAcc(tarAcc);

		try {
			if (bankService.addTransferTransation(transaction)) {
				model.addAttribute("successMessage",
						"Add a transaction successfully! To check your accounts remaining, please go to 'Accounts' section");
			} else {
				model.addAttribute("errorMessage",
						"Can not add this transaction! (Look in Business Logical)");
			}
		} catch (PersistenceException ex) {
			if (ex.getCause() instanceof ConstraintViolationException) {
				model.addAttribute("errorMessage",
						"Duplicated transaction found");
			} else {
				model.addAttribute("errorMessage",
						"Error adding new transaction");
			}
			LOG.error("Error found adding an transaction", ex);
			throw ex;
		} catch (Exception e) {
			LOG.error("General Error found adding an transaction", e);
			throw e;
		}

		return "forward:/listTransactions";
	}

	/**
	 * Lists all transactions of an account
	 */
	@RequestMapping(value = "/listTransactions")
	public ModelAndView listTransactions(HttpServletRequest request, Model model) {
		ModelAndView modelAndView = null;
		Customer currentCustomer = (Customer) request.getSession()
				.getAttribute("currentCustomer");

		// If user logged in, show transactions. Otherwise, go to home page
		if (currentCustomer != null) {

			// Create ModelAndView object
			modelAndView = new ModelAndView("transferMoney");

			// Get all the customer's account id to get all transactions
			String custLoginId = currentCustomer.getLoginid();

			// Get the list of all accounts from DB
			List<Account> accountList = bankService
					.getAccountsByCustomerId(custLoginId);

			// Get all accounts id of customer
			List<Integer> ids = new ArrayList<Integer>();
			for (Account account : accountList) {
				ids.add(account.getNumber());
			}

			// Get all transaction that has the sourceAccount that has the same
			// id with the customer account id
			List<TransferTransaction> transactions = new ArrayList<TransferTransaction>();
			for (Integer id : ids) {
				List<TransferTransaction> accTransactions = bankService
						.getTransferTransactionBySourceId(id);
				transactions.addAll(accTransactions);
			}

			modelAndView.addObject("sourceAccounts", accountList);
			modelAndView.addObject("transactions", transactions);

		} else {
			modelAndView = new ModelAndView("home");
		}
		return modelAndView;
	}

}
